package com.bsj.media.init;

import com.bsj.tools.netty.UdpServiceUntil;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author yinhao
 * @version 1.0
 * @description UDP链路,用于处理网关无法关闭设备回放
 * @date 2024/6/27
 */
@Slf4j
public class NettyUDPIntercomUntil {

    private static Map<Integer, UdpServiceUntil> channelMap = new ConcurrentHashMap<>();

    /**
     * 设备ID开启的回放端口集合
     */
    private static Map<Integer, List<Integer>> backPortMap = new ConcurrentHashMap<>();

    /**
     * 写入回放开启端口对应的UDP服务端缓存
     * @param port 回放端口
     * @param udpService UDP缓存
     */
    public static void push(Integer port, UdpServiceUntil udpService) {
        UdpServiceUntil udpServiceUntil = channelMap.get(port);
        if (udpServiceUntil == null) {
            channelMap.put(port, udpService);
        } else {
            channelMap.remove(port);
            channelMap.put(port, udpService);
        }
    }

    /**
     * 获取回放端口对应连接
     * @param port
     * @return
     */
    public static UdpServiceUntil gain(Integer port) {
        return channelMap.get(port);
    }

    /**
     * 删除回放对应连接
     * @param port
     */
    public static void del(Integer port) {
        UdpServiceUntil remove = channelMap.remove(port);
        if (remove != null) {
            log.info("回放UDP通道关闭: {}", port);
            remove.stop();
        }
    }

    /**
     * 写入设备ID对应的回放端口集合
     * @param devId 设备ID
     * @param port 端口号
     * @param udpService
     */
    public static void push(Integer devId, Integer port, UdpServiceUntil udpService) {
        push(port, udpService);
        List<Integer> list = backPortMap.get(devId);
        if (list == null) {
            list = new ArrayList<>();
        }
        list.add(port);
        backPortMap.put(devId, list);
    }

    public static void delPort(Integer devId, Integer port) {
        del(port);
        List<Integer> list = backPortMap.get(devId);
        if (list != null && list.isEmpty()) {
            list.remove(port);
            if (list.isEmpty()) {
                backPortMap.remove(devId);
            }
        }
    }

    public static List<Integer> gainPort(Integer devId) {
        return backPortMap.get(devId);
    }
}
